<template>
  <div v-loading="loading">
    <a-card>
      <title-name title="授权申请" />
      <a-form-model
        ref="ruleForm"
        :model="form4"
        :rules="form4Rules"
      >
        <a-row>
          <a-col span="24">
            <a-form-model-item label="合同名称">
              <BaseInput
                disabled
                :value="baseForm.contractName"
              />
            </a-form-model-item>
          </a-col>
          <a-col span="16">
            <a-form-model-item label="所属单位">
              <BaseInput
                disabled
                :value="baseForm.branchComName+'/'+baseForm.projectName"
              />
            </a-form-model-item>
          </a-col>

          <!-- <a-col span="8">
            <a-form-model-item label="所属分公司">
              <BaseInput
                disabled
                :value="baseForm.branchComName"
              />
            </a-form-model-item>
          </a-col>
          <a-col span="8">
            <a-form-model-item label="项目名称">
              <BaseInput
                disabled
                :value="baseForm.projectName"
              />
            </a-form-model-item>
          </a-col> -->
          <a-col span="8">
            <a-form-model-item label="业主名称">
              <BaseInput
                disabled
                :value="baseForm.otherParty"
              />
            </a-form-model-item>
          </a-col>
          <a-col span="8">
            <a-form-model-item label="合同额（万元）">
              <BaseInput
                disabled
                :value="baseForm.amount"
              />
            </a-form-model-item>
          </a-col>
          <a-col span="8" >
            <a-form-model-item
              :label="baseForm.linearIs?'建筑规模（km）':'建筑规模（m²）'"
              prop="buildingScale"
            >
              <BaseInputNumber
                v-model="form4.buildingScale"
                :disabled="isView"
                :min="0"
                :precision="2"
              />
            </a-form-model-item>
          </a-col>
          <a-col span="8">
            <a-form-model-item
              label="工程类别"
              prop="projectTypeId"
            >
              <BSelect v-model="form4.projectTypeId" :request="()=>getTypeLabel(31)"/>
            </a-form-model-item>
          </a-col>
          <a-col span="8">
            <a-form-model-item
              label="开竣工时间"
              prop="start"
            >
              <a-range-picker
                v-model="form4.start"
                :disabled="isView"
                value-format="x"
              />
            </a-form-model-item>
          </a-col>
          <a-col span="8">
            <a-form-model-item
              label="受托人姓名"
              prop="trusteeName"
            >
              <SelectUndertaking
                v-model="form4.trusteeName"
                :disabled="isView"
                placeholder="请输入受托人姓名"
                @change="getPerson"
              />
              <!-- <a-input-search
                v-model="form4.trusteeName"
                @click="$refs.personList.open()"
                @search="$refs.personList.open()"
              /> -->
            </a-form-model-item>
          </a-col>
          <a-col span="8">
            <a-form-model-item
              label="身份证"
            >
              <BaseInput
                v-model="form4.trusteeIdCard"
                :disabled="isView"
              />
            </a-form-model-item>
          </a-col>
          <a-col span="8">
            <a-form-model-item
              label="单位及部门"
              prop="trusteeOrgName"
            >
              <!-- <a-select v-model="form4.trusteeOrgId">
                <a-select-option v-for="item of trusteeOrgIdList" :key="item.key" :value="item.orgId">
                  {{ item.orgName }}
                </a-select-option>
              </a-select> -->
              <BaseInput
                v-model="form4.trusteeOrgName"
                disabled
                placeholder="请先选择受托人"
              />
            </a-form-model-item>
          </a-col>
          <a-col span="8">
            <a-form-model-item
              label="职务"
              prop="trusteePostName"
            >
              <!-- <a-select v-model="form4.trusteePostId">
                <a-select-option v-for="item of trusteeOrgIdList" :key="item.key" :value="item.id">
                  {{ item.name }}
                </a-select-option>
              </a-select> -->
              <BaseInput
                v-model="form4.trusteePostName"
                disabled
                placeholder="请先选择受托人"
              />
            </a-form-model-item>
          </a-col>
          <a-col span="8">
            <a-form-model-item
              label="授权书有效期"
              prop="authorizationTime"
            >
              <a-range-picker
                v-model="form4.authorizationTime"
                :disabled="isView"
                value-format="x"
              />
            </a-form-model-item>
          </a-col>
          <a-col span="8">
            <a-form-model-item label="授权书格式">
              <a-radio-group
                v-model="form4.letterOfAuthorizationId"
                :disabled="isView"
              >
                <a-radio
                  v-for="item of selectOptionList.auth"
                  :key="item.id"
                  :value="item.id"
                >
                  {{ item.name }}
                </a-radio>
              </a-radio-group>
            </a-form-model-item>
          </a-col>
          <a-col span="8">
            <a-form-model-item label="是否公证">
              <a-radio-group
                v-model="form4.notarization"
                :disabled="isView"
              >
                <a-radio value="1">
                  是
                </a-radio>
                <a-radio value="0">
                  否
                </a-radio>
              </a-radio-group>
            </a-form-model-item>
          </a-col>
          <a-col span="24">
            <a-form-model-item
              label="授权权限"
              prop="authorization"
            >
              <BaseTextarea
                v-model="form4.authorization"
                :disabled="isView"
                :auto-size="{ minRows: 2, maxRows: 4 }"
              />
            </a-form-model-item>
          </a-col>
          <a-col span="8">
            <a-form-model-item
              label="办理份数（中）"
              prop="chinese"
            >
              <BaseInputNumber
                v-model="form4.chinese"
                :disabled="isView"
                :min="0"
              />
            </a-form-model-item>
          </a-col>
          <a-col span="8">
            <a-form-model-item
              label="办理份数（英）"
              prop="english"
            >
              <BaseInputNumber
                v-model="form4.english"
                :disabled="isView"
                :min="0"
              />
            </a-form-model-item>
          </a-col>
          <a-col span="8">
            <a-form-model-item
              label="办理份数（其他）"
              prop="others"
            >
              <BaseInputNumber
                v-model="form4.others"
                :disabled="isView"
                :min="0"
              />
            </a-form-model-item>
          </a-col>
          <a-col span="8">
            <a-form-model-item
              label="完成时间"
            >
              <a-date-picker
                v-model="form4.completeTime"
                :disabled="isView"
                value-format="x"
              />
            </a-form-model-item>
          </a-col>
          <a-col span="8">
            <a-form-model-item label="申请人">
              <a-input
                v-model="form4.applicantName"
                disabled
              />
            </a-form-model-item>
          </a-col>
          <a-col span="8">
            <a-form-model-item
              label="申请时间"
              prop="applyTime"
            >
              <a-date-picker
                v-model="form4.applyTime"
                :disabled="isView"
                value-format="x"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </a-card>
    <a-card>
      <title-name title="附件" />
      <u-table
        :is-show="!form4.authorizationStatus || form4.authorizationStatus === 'DRAFT'"
        business-code="LCM08"
        :is-upload="false"
        :file-arrys.sync="form4.fileInfos"
        :upload-arrys="uploadArrys"
      />
    </a-card>
    <div class="operation page-btn-right-top">
    <!-- <div class="operation mb20p mr20p tar"> -->
      <template v-if="form4.authorizationStatus !== 'SUBMITTED'">
        <a-button
          type="primary"
          class="mr10p"
          @click="save('DRAFT')"
        >
          保存草稿
        </a-button>
        <a-button
          type="primary"
          class="mr10p"
          @click="submit"
        >
          提交
        </a-button>
      </template>
      <a-button @click="$close()">
        关闭
      </a-button>
    </div>
    <!-- <person-list
      ref="personList"
      @getPerson="getPerson"
    /> -->
    <selectApprover :businessId="businessId"  :processConfig="setProcessConfig"></selectApprover>
  </div>
</template>

<script>
import totalPackageContractApi from '@/api/legal/branchContract/totalPackageContract'
import { getInfoByStaffId } from '@/api/commons'
import SelectUndertaking from '@/components/Select/SelectUndertaking'
import { createValidator, idCard } from '@/utils/regExpression' // 正则校验

export default {
  name: 'AuthApply',
  components: {
    SelectUndertaking
  },
  props: {
    baseForm: {
      type: Object
    },
    selectOptionList: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    return {
      getTypeLabel: type => totalPackageContractApi.typeslabel({ pageNo: 0, pageSize: 100000, query: { type } }),
      loading: false,
      uploadArrys: [],
      form4: {
        letterOfAuthorizationId: '',
        notarization: '',
        trusteeIdCard: void 0,
        applicantName: void 0
      },
      form4Rules: {
        buildingScale: [{ required: true, message: '请填写建筑规模', trigger: 'blur' }],
        projectTypeId: [{ required: true, message: '请填写工程类别', trigger: 'blur' }],
        start: [{ required: true, message: '请填写开竣工时间', trigger: 'change' }],
        trusteeName: [{ required: true, message: '请选择受托人姓名', trigger: 'change' }],
        trusteeOrgId: [{ required: true, message: '请填写单位及部门', trigger: 'blur' }],
        trusteePostId: [{ required: true, message: '请填写职务', trigger: 'blur' }],
        authorizationTime: [{ required: true, message: '请填写授权书有效期', trigger: 'change' }],
        authorization: [{ required: true, message: '请填写授权权限', trigger: 'blur' }],
        chinese: [{ required: true, message: '请填写办理份数（中）', trigger: 'blur' }],
        english: [{ required: true, message: '请填写办理份数（英）', trigger: 'blur' }],
        others: [{ required: true, message: '请填写办理份数（其他）', trigger: 'blur' }],
        completeTime: [{ required: true, message: '请填写完成时间', trigger: 'change' }],
        trusteeIdCard: [
          { required: true, validator: createValidator(idCard, '请输入正确的身份证号码', true), trigger: 'blur' }
        ],
        // applicantName: [{ required: true, message: '请填写申请人', trigger: 'blur' }],
        applyTime: [{ required: true, message: '请填写申请时间', trigger: 'change' }]
      },
      trusteeOrgIdList: [],
      //获取流程配置值
      processConfig: null,
      //点击提交发送流程配置值
      setProcessConfig: null,
      businessId: null
    }
  },
 async created() {
    let { name } = this.$userInfo()
    this.form4.applicantName = name
    this.getData()
    //获取通过获取流程配置值
    this.processConfig = await this.$getConfigFn('legal_general_applyforauthority_new');
  },
  computed: {
    // 是否为查看；当授权申请状态存在且不为草稿状态，只能查看表单
    isView() {
      return (
        this.form4.authorizationStatus &&
        this.form4.authorizationStatus !== 'DRAFT' &&
        this.form4.authorizationStatus !== 'REJECTED'
      )
    }
  },
  methods: {
    async getPerson(row) {
      let label = row.label?.split(':')?.[1]?.split('/') // label
      let trusteeOrgName = label?.slice(0, label.length - 1).join('-')
      let trusteePostName = label[label.length - 1]
      this.form4.trusteeId = row.employeeId || void 0
      row.idCard && (this.form4.trusteeIdCard = row.idCard)
      this.form4.trusteeOrgName = trusteeOrgName
      this.form4.trusteePostName = trusteePostName
    },
    async getData() {
      if (this.baseForm.baseId) {
        this.loading = true
        let res = await totalPackageContractApi.findApplyForAuthorityByBaseId(
          {},
          {
            edit: true,
            baseId: this.baseForm.baseId
          }
        )
        if (res.code === 200) {
          if (res.data.trusteeName) {
            res.data.trusteeName = {
              key: res.data.trusteeId,
              label: res.data.trusteeName
            }
          } else {
            delete res.data.trusteeName
          }
          if (!res.data.applicantName) {
            res.data.applicantName = this.$userInfo().name
          }
          if (res.data.fileInfos?.length > 0) {
            this.uploadArrys = res.data.fileInfos
          }
          this.form4 = res.data
          if (res.data.startTime) {
            this.form4.start = [res.data.startTime, this.form4.endTime]
          }
          if (res.data.authorizationTimeStartTime) {
            this.form4.authorizationTime = [res.data.authorizationTimeStartTime, this.form4.authorizationTimeEndTime]
          }

          if (res.data.trusteeUserId) {
            let res2 = await getInfoByStaffId(res.data.trusteeUserId)
            if (res2.data) {
              res2.data.posts.map((v) => {
                v.key = Date.now()
                v.key2 = Date.now() + '' + Date.now()
              })
              this.trusteeOrgIdList = res2.data.posts
            }
          }
        }
        this.loading = false
      }
    },
    async submit() {
      if (!(await this.save('DRAFT', true))) {
        return
      }
      // this.$bus.$emit('submit', '1121', '0')
    },
    async save(status, isSubmit = false) {
      this.setProcessConfig = null; 
      this.submitApprovalConfirm(status == 'SUBMITTED'?this.processConfig:6,(flag)=>{
        if(!flag) {
            this.loading = false
            return
          }
        return new Promise((resolve) => {
        let form = this.$clone(this.form4)
        if (form.start && form.start.length) {
          form.startTime = form.start[0]
          form.endTime = form.start[1]
        }
        if (form.authorizationTime && form.authorizationTime.length) {
          form.authorizationTimeStartTime = form.authorizationTime[0]
          form.authorizationTimeEndTime = form.authorizationTime[1]
        }
        form.authorizationStatus = status
        if (form.trusteeName) {
          form.trusteeId = form.trusteeName.key
          form.trusteeName = form.trusteeName.label
        }
        if (!form.letterOfAuthorizationId) return this.$noticeWarning('请选择授权书格式')
        if (!form.notarization) return this.$noticeWarning('请选择是否公证')
        form.applicantName = JSON.parse(sessionStorage.getItem('ycloud-user_info')).name
        form.applicantEmployeeId = JSON.parse(sessionStorage.getItem('ycloud-user_info')).employee.userId

        this.$refs.ruleForm.validate(async (valid, object) => {
          if (valid) {
            this.loading = true
            form.baseId = this.baseForm.baseId
            let res = await totalPackageContractApi.updateApplyForAuthority(form)
            if (res.code === 200) {

              if (isSubmit) {
                //提交时，返回id
                  let res1 = await totalPackageContractApi.generalSubmit({
                        auditStatusEnum: 'SUBMITTED',
                        baseId: this.baseForm.baseId,
                        majorRisks: '0',
                        submitCode: '1121'
                    })
                //resolve(true)
                this.businessId = res1.data?.businessId;
                this.setProcessConfig = this.processConfig;
              } else {
                this.$noticeSuccess('保存成功')
                this.$close()
              }
            }
            this.loading = false
          } else {
            this.$noticeWarning('请填写完整')
          }
        })
      })
      })

    }
  }
}
</script>

<style lang="less" scoped>
/deep/.ant-form-item {
  .ant-form-item-label {
    width: 150px;
  }
  .ant-form-item-control-wrapper {
    width: calc(100% - 150px);
  }
}
</style>
